import axios, {AxiosError, AxiosRequestConfig, AxiosResponse} from 'axios';
import {message} from 'ant-design-vue';
import util from '@/utils/util';
import config from '@/config.ts';
//import router from '@/router';

const service = axios.create({
    timeout: 10000,
});

service.interceptors.request.use((config: AxiosRequestConfig) => {
    return config;
});

service.interceptors.response.use((response: AxiosResponse) => {
    return response;
}, (err: AxiosError) => {
    let errMsg = '';
    if (err.response) {
        switch (err.response.status) {
            case 401:
                errMsg = '登录状态失效，请重新登录';
                break;
            case 403:
                errMsg = '拒绝访问';
                break;
            case 408:
                errMsg = '请求超时';
                break;
            case 500:
                errMsg = '服务器内部错误';
                break;
            case 501:
                errMsg = '服务未实现';
                break;
            case 502:
                errMsg = '网关错误';
                break;
            case 503:
                errMsg = '服务不可用';
                break;
            case 504:
                errMsg = '网关超时';
                break;
            case 505:
                errMsg = 'HTTP版本不受支持';
                break;
            default:
                errMsg = err.response.data.msg;
                break;
        }
    }
    return Promise.reject(errMsg);
});

const request = async (...args: any): Promise<TypeBase.RequestResult<any>> => {
    const requestFn = async (...arr: any): Promise<TypeBase.RequestResult<any>> => {
        let conf: TypeRequest.RequestConfig = {};
        let extendConf: TypeRequest.ExtendConf = {
            prefix: '/api/',
            loading: false,
        };
        // 基础配置
        if (arr[0]) {
            conf = arr[0];
        }
        // 判断是否传入扩展配置
        if (arr[1] && util.isObject(arr[1])) {
            extendConf = Object.assign(extendConf, arr[1]);
        }
        let method: string = 'POST';
        if (conf.method) {
            method = conf.method.toUpperCase();
        }

        conf.headers = {...conf.headers};
        // 设置基础url
        conf.baseURL = config.baseURL + extendConf.prefix;
        const params = util.deepCopy(conf.params || {});
        // 添加扩展参数
        if (method === 'GET') {
            // conf.params = extendSignData(params);
            conf.params = params;
        }
        // 检测网络链接
        if (!window.navigator.onLine) {
            return await Promise.reject({code: 504, data: null});
        }
        // if (extendConf.loading) {
        //     // 开启加载动画
        //     store.dispatch('setLoading', true);
        // }

        try {
            const res: any = await axios(conf);
            // 通用状态码判断
            if (res instanceof Blob) {
                return res;
            } else if (res.state !== 1) {
                res.message && message.error(res.message);
                return await Promise.reject(res);
            } else {
                return res;
            }
        } catch (e) {
            if (e instanceof Object && e.response) {
                const data = e.response.data;
                if (conf.showError !== false && extendConf.showError !== false && e.response.status === 400) {
                    data.message && message.error(data.message);
                }
                return await Promise.reject(e.response);
            }
            // // 请求超时
            // if (e.toString().indexOf('timeout') !== -1) {
            //     // 重试三次
            //     if (count < 3 && method.toUpperCase() === 'GET') {
            //         warn(tc('API timed out, retrying automatically...'), 5);
            //         count++;
            //         return await requestFn(...arr);
            //     } else {
            //         throw e;
            //     }
            // } else {
            //     throw e;
            // }
            throw e;
        }
    };
    return await requestFn(...args);
};


export default {
    /**
     * post请求
     * @param conf axios配置参数
     * @param extendConf 扩展配置参数
     * @returns 返回调数据类型
     */
    async get<T>(conf: TypeBase.RequestParams<T>, extendConf?: TypeRequest.ExtendConf): Promise<TypeBase.RequestResult<any>> {
        return await request({
            method: 'get',
            ...conf,
        }, extendConf);
    },
    /**
     * post请求
     * @param conf axios配置参数
     * @param extendConf 扩展配置参数
     * @returns 返回调数据类型
     */
    post<T>(conf: TypeBase.RequestParams<T>, extendConf?: TypeRequest.ExtendConf): Promise<TypeBase.RequestResult<any>> {
        return request({
            method: 'post',
            ...conf,
        }, extendConf);
    },
};
